package me.zhengjie.kwService.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.exception.ParameterException;
import me.zhengjie.kwService.GeneralExamService;
import me.zhengjie.kwService.SysUsersGeneralExamsService;
import me.zhengjie.mapper.*;
import me.zhengjie.pojo.dto.GeneralExamDto;
import me.zhengjie.pojo.entity.*;
import me.zhengjie.util.AssertUtils;
import me.zhengjie.util.BaseResponse;
import me.zhengjie.util.ruoyiexcel.StringUtils;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Description TODO
 * @Author Long
 * @Date 2021/8/12 14:55
 */
@Service
public class GeneralExamServiceImpl extends ServiceImpl<GeneralExamMapper, GeneralExam> implements GeneralExamService {

    @Autowired
    private GeneralExamMapper generalExamMapper;
    @Autowired
    private ExamTeacherMapper examTeacherMapper;
    @Autowired
    private ExamStudentMapper examStudentMapper;
    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SysUsersGeneralExamsMapper sysUsersGeneralExamsMapper;
    @Autowired
    private SysUsersGeneralExamsService sysUsersGeneralExamsService;

    /**
     * 分页查询总考试
     *
     * @param dto 查询条件
     */
    @Override
    public IPage<GeneralExam> findPage(GeneralExamDto dto) {
        /*获取当前登录用户*/
        UserDetails currentUser = SecurityUtils.getCurrentUser();
        String username = currentUser.getUsername();
        /*根据当前登陆用户名获取登录用户的id*/
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", username);
        User user = userMapper.selectOne(userQueryWrapper);
        Long userId = user.getUserId();
        /*根据登录用户id获取所关联的总考试*/
        QueryWrapper<SysUsersGeneralExams> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        List<SysUsersGeneralExams> sysUsersGeneralExams = sysUsersGeneralExamsMapper.selectList(queryWrapper);
        /*没有任何关联考试返回空*/
        if (sysUsersGeneralExams == null || sysUsersGeneralExams.isEmpty()) return new Page<>();
        Set<Long> generalIds = sysUsersGeneralExams.stream().map(SysUsersGeneralExams::getGeneralId).collect(Collectors.toSet());


        Page<GeneralExam> page = new Page<>(dto.getPage(), dto.getSize());
        QueryWrapper<GeneralExam> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(dto.getName()), "name", dto.getName())
                .ge(dto.getStartTime() != null, "start_time", dto.getStartTime())
                .le(dto.getEndTime() != null, "end_time", dto.getEndTime())
                .eq(dto.getGeneralExamNumber() != null, "general_exam_number", dto.getGeneralExamNumber())
                .in("id", generalIds);
        page = generalExamMapper.selectPage(page, wrapper);
        /*查询本场总考试下的汇总监考老师人数和汇总考生人数和总场次*/
        for (GeneralExam generalExam : page.getRecords()) {
            Integer id = generalExam.getId();


            QueryWrapper<Exam> examQueryWrapper = new QueryWrapper<>();
            examQueryWrapper.eq("general_id", id);
            List<Exam> exams = examMapper.selectList(examQueryWrapper);
            /*设置总考试的场次数*/
            generalExam.setExams(exams == null || exams.isEmpty() ? 0 : exams.size());

            LinkedList<Integer> list = new LinkedList<>();
            if (exams != null && !exams.isEmpty()) {
                for (Exam exam : exams) {
                    list.add(exam.getId());
                }
            }
            if (!list.isEmpty()) {
                QueryWrapper<ExamTeacher> examTeacherQueryWrapper = new QueryWrapper<>();
                examTeacherQueryWrapper.in("exam_id", list).select("distinct (teacher_id)");
                List<ExamTeacher> examTeachers = examTeacherMapper.selectList(examTeacherQueryWrapper);
                if (examTeachers != null && examTeachers.size() > 0)
                    generalExam.setExamTearchers(examTeachers.size());
                else generalExam.setExamTearchers(0);
                QueryWrapper<ExamStudent> examStudentQueryWrapper = new QueryWrapper<>();
                examStudentQueryWrapper.in("exam_id", list).select("distinct (student_id)");
                List<ExamStudent> examStudents = examStudentMapper.selectList(examStudentQueryWrapper);
                if (examStudents != null && examStudents.size() > 0)
                    generalExam.setExamStudents(examStudents.size());
                else generalExam.setExamStudents(0);
            }else {
                generalExam.setExamStudents(0);
                generalExam.setExamTearchers(0);
            }

        }
        return page;
    }

    /**
     * 根据总考试id查询单个总考试
     *
     * @param id 总考试id
     * @return 总考试
     */
    @Override
    public GeneralExam findOne(Integer id) {
        return generalExamMapper.selectById(id);
    }

    /**
     * 批量删除总考试
     *
     * @param ids 总考试id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse deleteBatch(List<Integer> ids) {
        AssertUtils.isNotEmpty(ids, "请选择考试");
        for (Integer id : ids) {
            QueryWrapper<Exam> examQueryWrapper = new QueryWrapper<>();
            examQueryWrapper.eq("general_id", id);
            List<Exam> exams = examMapper.selectList(examQueryWrapper);
            if (!exams.isEmpty()) {
                GeneralExam generalExam = generalExamMapper.selectById(id);
                throw new ParameterException(generalExam.getName() + "考试存在考场信息不允许删除");
            }
            generalExamMapper.deleteById(id);
        }
        sysUsersGeneralExamsService.deleteBatch(ids);
        return BaseResponse.ok();

    }

    /**
     * 删除总考试下的所有考生
     *
     * @param ids
     */
    @Override
    public BaseResponse deleteAllKwStudent(List<Long> ids) {
        AssertUtils.isNotEmpty(ids, "总考试id不可为空");
        QueryWrapper<Exam> wrapper = new QueryWrapper<>();
        wrapper.in("general_id", ids);
        List<Exam> exams = examMapper.selectList(wrapper);
        if (exams == null || exams.isEmpty()) return BaseResponse.ok();
        List<Integer> list = exams.stream().map(Exam::getId).collect(Collectors.toList());
        QueryWrapper<ExamStudent> examStudentQueryWrapper = new QueryWrapper<>();
        examStudentQueryWrapper.in("exam_id", list);
        examStudentMapper.delete(examStudentQueryWrapper);
        return BaseResponse.ok();
    }

    /**
     * 查询所有考试
     *
     * @return
     */
    @Override
    public BaseResponse findAll() {
        return BaseResponse.ok(generalExamMapper.selectList(null));
    }
}
